package com.shh.rabbitmq.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.shh.rabbitmq.dao.OrderMsgDao;
import com.shh.rabbitmq.domin.OrderDO;
import com.shh.rabbitmq.domin.OrderMsgDO;

@Component
public class RabbitTemplateConfig implements RabbitTemplate.ConfirmCallback{    
	
	@Autowired
    private RabbitTemplate rabbitTemplate; 
	
	@Autowired
	private OrderMsgDao orderMsgDao;
	
	public void send(OrderDO orderDO) {
        // 封装消息
        Message message = MessageBuilder.withBody(JSON.toJSONString(orderDO).getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(orderDO.getOrderNo()).build();
        // 构建回调返回的数据
        CorrelationData correlationData = new CorrelationData(orderDO.getOrderNo());
        // 发送消息
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.convertAndSend("direct_order_exchange", "order", message, correlationData);

    }
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
    	//判断是否发送到交换机，如果发送则更改订单消息状态为1
    	if(ack) {
    		OrderMsgDO orderMsg = new OrderMsgDO();
    		orderMsg.setOrderNo(correlationData.getId());
    		orderMsg.setOrderState(1);
    		orderMsgDao.updateModel(orderMsg);
    		System.out.println("订单消息发送成功");
    	}
    }

}